package com.clss.emergencycall.base;

import android.os.Handler;
import android.os.Looper;

import com.clss.emergencycall.bean.BaseJson;
import com.clss.emergencycall.tools.eventbus.EventBusHelper;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public abstract class OkBaseCallBack implements Callback{

    private BaseView mBaseView;

    public OkBaseCallBack(BaseView baseView) {
        mBaseView = baseView;
    }

    @Override
    public void onFailure(Call call, IOException e) {
        mBaseView.dismissLoadingDialog();
        mBaseView.requestFailure(e);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String res = response.body().string();
        BaseJson baseJson = new Gson().fromJson(res, BaseJson.class);
        EventBusHelper.handleBaseJson(baseJson);
        new Handler(Looper.getMainLooper()).post(() -> {
            mBaseView.dismissLoadingDialog();
            if (baseJson != null){
                if (baseJson.getCode() != 0){
                    if (baseJson.getCode() == 99){
                        return;
                    }
                    mBaseView.responseError(baseJson.getCode(), baseJson.getError());
                }else {
                    responseSuccess(baseJson);
                }
            }else {
                mBaseView.responseError(Constant.UNKNOW_ERROR_CODE, Constant.UNKNOW_ERROR_MESSAGE);
            }
        });
    }

    public abstract void responseSuccess(BaseJson baseJson);
}
